template 與 layout 非常的相似,都是用來顯示共享 UI,也可巢狀的使用它。
差別只在於 template 在每次換頁時會重新生成一個實例,所以當中的狀態是不會保留的。
它最後輸出的結果會類似於底下的形式,在每次換頁時 key 都會因為 route 更改的不同,重新再渲染一次
<Layout>
{/* Note that the template is given a unique key. */}
<Template key={routeParam}>{children}</Template>
</Layout>
建立 template 檔案
export default with children
export default function Template({ children }: { children: React.ReactNode }) {
return <div>{children}</div>
}
某些 useEffect 是每次換頁時都要觸發,或是需要某些 state 是換頁時需要重新計算的。
比方說 layout 只有在首次選染時會渲染 Suspense 的 fallback UI,之後換頁就不會再重新渲染 fallback UI 的部分。
但使用 template 就可以在每次換頁時都顯示 Suspence 的 fallback UI。